<?php
namespace app\api\controller;

use app\common\controller\BaseController;
use app\common\repositories\users\UsersRepository;
use app\common\repositories\merchant\MerchantRepository;
use support\Container;
use support\Request;
use app\api\middleware\SecurityMiddleware;

/**
 * 统一身份认证控制器
 * 整合用户端和商户端的登录认证体系
 */
class AuthController extends BaseController
{
    protected $userRepository;
    protected $merchantRepository;

    public function __construct()
    {
        $this->userRepository = new UsersRepository();
        $this->merchantRepository = new MerchantRepository();
    }

    /**
     * 统一登录接口
     * @api {post} /auth/login 统一登录
     * @apiParam {String} email 邮箱地址
     * @apiParam {String} password 密码
     * @apiParam {String} user_type 用户类型 (user|merchant)
     */
    public function login()
    {
        $email = request()->post('email');
        $password = request()->post('password');
        $userType = request()->post('user_type', 'user'); // 默认为用户端登录

        if (!$email || !$password) {
            return json(['code' => 400, 'msg' => '邮箱和密码不能为空']);
        }

        // 根据用户类型选择不同的认证方式
        $result = null;
        switch ($userType) {
            case 'merchant':
                $result = $this->merchantRepository->loginMerchant($email, $password);
                if ($result['code'] === 200) {
                    // 添加用户类型标识
                    $result['data']['user_type'] = 'merchant';
                    $result['data']['login_type'] = 'unified';
                }
                break;
            
            case 'user':
            default:
                $result = $this->userRepository->loginOneUsers($email, $password);
                if ($result['code'] === 200) {
                    // 添加用户类型标识
                    $result['data']['user_type'] = 'user';
                    $result['data']['login_type'] = 'unified';
                }
                break;
        }

        // 如果登录失败，记录失败尝试（通过中间件处理）
        if ($result['code'] !== 200) {
            // 设置失败信息到请求中，供安全中间件处理
            $request->failed_login_attempt = [
                'ip' => request()->getRealIp(),
                'username' => $email,
                'timestamp' => time()
            ];
        }

        return json($result);
    }

    /**
     * 统一注册接口
     * @api {post} /auth/register 统一注册
     * @apiParam {String} email 邮箱地址
     * @apiParam {String} password 密码
     * @apiParam {String} user_type 用户类型 (user|merchant)
     * @apiParam {Object} additional_data 额外注册信息
     */
    public function register()
    {
        $email = request()->post('email');
        $password = request()->post('password');
        $userType = request()->post('user_type', 'user');
        $additionalData = request()->post('additional_data', []);

        if (!$email || !$password) {
            return json(['code' => 400, 'msg' => '邮箱和密码不能为空']);
        }

        switch ($userType) {
            case 'merchant':
                // 商户注册需要额外信息
                $requiredFields = ['company_name', 'contact_name', 'phone'];
                foreach ($requiredFields as $field) {
                    if (empty($additionalData[$field])) {
                        return json(['code' => 400, 'msg' => "商户注册缺少必要字段: {$field}"]);
                    }
                }

                $merchantData = [
                    'company_name' => $additionalData['company_name'],
                    'contact_name' => $additionalData['contact_name'],
                    'email' => $email,
                    'phone' => $additionalData['phone'],
                    'password' => $password,
                    'password_confirm' => $password
                ];

                $result = $this->merchantRepository->registerMerchant($merchantData);
                break;
            
            case 'user':
            default:
                $result = $this->userRepository->registerOneUsers($email, $password);
                break;
        }

        return json($result);
    }

    /**
     * 获取当前登录用户信息（统一接口）
     * @api {get} /auth/me 获取当前用户信息
     */
    public function me()
    {
        $user = request()->user ?? null;
        $userType = request()->user_type ?? 'user';

        if (!$user) {
            return json(['code' => 401, 'msg' => '用户未登录']);
        }

        // 根据用户类型返回不同的信息结构
        if ($userType === 'merchant') {
            $userInfo = [
                'id' => $user['id'],
                'company_name' => $user['company_name'],
                'email' => $user['email'],
                'contact_name' => $user['contact_name'],
                'status' => $user['status'],
                'user_type' => 'merchant'
            ];
        } else {
            $userInfo = [
                'id' => $user['id'],
                'email' => $user['email'],
                'nickname' => $user['nickname'] ?? $user['email'],
                'avatar' => $user['avatar'] ?? '',
                'user_type' => 'user'
            ];
        }

        // 添加会员信息
        $membershipInfo = Container::make(\app\common\service\MembershipService::class)->getAppLimitInfo($user['id']);
        $userInfo['membership'] = $membershipInfo;

        return json(['code' => 200, 'data' => $userInfo]);
    }

    /**
     * 统一登出接口
     * @api {post} /auth/logout 统一登出
     */
    public function logout()
    {
        $user = request()->user ?? null;
        $userType = request()->user_type ?? 'user';

        if ($user) {
            // 根据用户类型执行登出操作
            if ($userType === 'merchant') {
                // 商户登出逻辑（如果有的话）
                $this->merchantRepository->logout($user['id']);
            } else {
                // 用户登出逻辑
                $this->userRepository->loginout($user['id']);
            }
        }

        return json(['code' => 200, 'msg' => '登出成功']);
    }

    /**
     * 检查用户类型
     * @api {post} /auth/check-user-type 检查用户类型
     * @apiParam {String} email 邮箱地址
     */
    public function checkUserType()
    {
        $email = request()->post('email');

        if (!$email) {
            return json(['code' => 400, 'msg' => '邮箱地址不能为空']);
        }

        // 检查是否是商户
        $merchant = $this->merchantRepository->getMerchantByEmail($email);
        if ($merchant) {
            return json([
                'code' => 200, 
                'data' => [
                    'exists' => true,
                    'user_type' => 'merchant',
                    'status' => $merchant['status']
                ]
            ]);
        }

        // 检查是否是普通用户
        $user = $this->userRepository->getUserByEmail($email);
        if ($user) {
            return json([
                'code' => 200, 
                'data' => [
                    'exists' => true,
                    'user_type' => 'user',
                    'status' => 'active'
                ]
            ]);
        }

        return json([
            'code' => 200, 
            'data' => [
                'exists' => false,
                'user_type' => null
            ]
        ]);
    }
}